package org.wlgzs.moyue.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;
import org.wlgzs.moyue.dao.BookDao;
import org.wlgzs.moyue.dao.BookListDao;
import org.wlgzs.moyue.entity.Book;
import org.wlgzs.moyue.entity.BookList;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Auther: dayfly
 * @Date: 2018/4/25 21:10
 * @Description: 用于包括头像上传，书籍上传，章节上传,以及下载问题
 */
public class IoUtil {
    @Autowired
    private BookListDao bookListDao;
    @Autowired
    private BookDao bookDao;

    final String fileUrl = "static/upload/book/";

    //解析txt的章节
    public List<BookList> analysis(Book book) {
        List<BookList> bookLists = new ArrayList<>();
        BookList bookList = new BookList();
        try {
            FileReader fileReader = new FileReader(new File("." + book.getBookUrl()));
            BufferedReader reader = new BufferedReader(fileReader, 1024 * 1000);
            int i = 0;
            String str = reader.readLine();
            while (str != null) {
                if (this.mateStart(str)) {
                    bookList.setBookListName(str.split(" ")[1]);          //通过匹配类型“ ”来获取章节名字，并存入
                    String pathurl = "/upload/book/" + book.getBookId() + "/booklist/" + Integer.toString(i) + ".txt";
                    String filePath = "." + pathurl;
                    File file1 = new File(filePath);
                    file1.getParentFile().mkdirs();
                    FileWriter fileWriter = new FileWriter(file1);
                    str = reader.readLine();
                    String data = "";
                    do {
                        data += str + "\r\n";
                        str = reader.readLine();
                    } while (!this.mateEnd(str));
                    fileWriter.write(data);
                    fileWriter.flush();
                    fileWriter.close();
                    bookList.setBookListUrl(pathurl);
                    bookList.setBookListOrder(i);
                    bookList.setBookId(book.getBookId());
                    bookList.setBookListSize(data.length());
                    bookLists.add(bookList);
                    i++;
                }
                str = reader.readLine();
            }
            reader.close();
            fileReader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            bookLists.clear();
        } catch (IOException e) {
            e.printStackTrace();
            bookLists.clear();
        }
        return bookLists;
    }


    //作者网页创作内容的写入书籍目录文件夹
    public BookList saveBookList(BookList bookList, String content) {
        Book book = bookDao.findById(bookList.getBookId()).get();
        String saveUrl = "/upload/book/" + book.getBookId() + "/booklist/" + book.getBookListCount() + 1 + ".txt";
        try {
            File file = new File(saveUrl);
            file.createNewFile();
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(content);
            fileWriter.flush();
            fileWriter.close();
            bookList.setBookListSize(content.length());
            bookList.setBookListUrl(saveUrl);
            bookListDao.save(bookList);
            return bookList;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    //作者网页创作内容写入书记总txt
    public Book appendBook(BookList bookList, String content) {
        String title = "第" + (bookDao.findById(bookList.getBookId()).get().getBookListCount() + 1) + "章 " + bookList.getBookListName();
        Book book = bookDao.findById(bookList.getBookId()).get();
        try {
            FileWriter fileWriter = new FileWriter(new File(book.getBookUrl()), true);
            fileWriter.write(title + "\n\n");
            fileWriter.write(content + "\n");
            fileWriter.write("---------" + "\n\n");
            fileWriter.flush();
            fileWriter.close();
            book.setBookWordCount(book.getBookListCount() + content.length());
            book.setBookListCount(book.getBookListCount() + 1);
            return book;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    //文件写入
    public boolean saveFile(MultipartFile file, String filePath) {
        try {
            if (!file.isEmpty()) {
                File saveFile = new File("." + filePath);
                if (!saveFile.getParentFile().exists()) {
                    saveFile.getParentFile().mkdirs();
                }
                FileOutputStream outputStream = new FileOutputStream(saveFile);
                BufferedOutputStream out = new BufferedOutputStream(outputStream);
                out.write(file.getBytes());
                out.flush();
                out.close();
                outputStream.close();
                return true;
            }
            return false;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    public void deleteFile(String url) {
        File file = new File("." + url);
        if (file.exists()) file.delete();
    }

    //正则表达式匹配”第几章“，即一章的开始
    public static boolean mateStart(String str) {
        if (str == null) return false;
        String pattern = "第.*?章";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        return m.find();
    }

    //正则表达式匹配”-------“，即一章的结束
    public static boolean mateEnd(String str) {
        if (str == null) return false;
        String pattern = "-----";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        return m.find();
    }


}